﻿/*Author：Lary Pan(itolmqj123@gmail.com)
 *Date  ：2016/8/14
 *Tips  ：DB Adapter
 * */

using System;
using System.Text;
using System.Collections.Generic;
using System.Reflection;

public class DBAdapter
{
    public List<DBParam> list = new List<DBParam>();

    public static DBAdapter Inst { get { return new DBAdapter(); } }

    public DBAdapter Add(string key, object obj, CompareType queryType = CompareType.Equal)
    {
        list.Add(new DBParam(key, obj, queryType));
        return this;
    }

    public bool IsSatisfy<T>(EntityBase entity) where T : EntityBase
    {
        bool flg = true;
        Type t = typeof(T);
        DBParam param = null;
        for (int i = 0; i < list.Count; i++)
        {
            param = list[i];
            FieldInfo info = t.GetField(param.key);
            object value = info.GetValue(entity);

            flg = flg && param.IsSatisfy(value);
            if (!flg) return false;
        }
        return flg;
    }

    public void UpdateValue<T>(ref EntityBase entity) where T : EntityBase
    { 
        Type t = typeof(T);
        DBParam param = null;
        for (int i = 0; i < list.Count; i++)
        {
            param = list[i];
            FieldInfo info = t.GetField(param.key);
            info.SetValue(entity, param.value);
        }
    }
    //private string[] compareTypeArr = { "=", "==", "<>", ">", ">=", "<", "<=" };
    
    //public string ToString()
    //{
    //    StringBuilder sb = new StringBuilder();
    //    foreach (DBParam param in list)
    //    {
    //        string fm = (param.value is string) ? " {0} {1} '{2}'," : " {0} {1} {2},";
    //        sb.AppendFormat(fm, param.key, compareTypeArr[(int)param.type], param.value);
    //    }
    //    return sb.ToString(0, sb.Length - 1);
    //}

}